import storys from '@/models/storys';
import { addRelative } from '@/services/storyWithproject';
import { tapd2types, onlineStoryStatus } from '@/utils/data';
import { sonarOApiFetch } from '../fetch';
import { getSingleBranch } from '../gitlab/apis';
import { privateToken } from '../configs/gitlab';
import { syncProjectsSearch } from '../gitlab/index';
import { getWeeks, getMonths } from './utils';

const sonarApi = sonarOApiFetch();

const convertKey = (arr) => {
  const newArr: any = [];
  for (let i = 0; i < arr.length; i += 1) {
    const obj = {};
    Object.keys(arr[i]).forEach((item) => {
      if (tapd2types[item]) {
        obj[tapd2types[item]] = arr[i][item];
      }
    });
    newArr.push(obj);
  }
  return newArr;
};

// 获取所有列表
export const syncStorySearch = async (params: any) => {
  const { page = 1, pageSize = 10 } = params;
  // 名称。正则模糊查询
  const query: any = {};
  if (params.name) {
    query.name = new RegExp(params.name);
  }
  // 需求状态
  if (params.status) {
    query.status = params.status;
  }
  // 需求id
  if (params.id) {
    query.id = params.id;
  }
  // 上线日期
  if (params.online_time) {
    query.online_time = params.online_time;
  }
  // 按周查询，按月查询
  let times: string[] = [];
  if (params.timeCondition) {
    if (params.timeCondition === 'week') {
      times = getWeeks(); // 返回每周的日期
    } else if (params.timeCondition === 'month') {
      times = getMonths(); // 返回一个月的日期，月初到月底
      console.log(times);
    }
  }
  if (params.isAll) {
    // 'status_5', 'status_8' 'status_7' 发布完成 已归档，完成目标review。给首页看板列表使用
    const list = await storys.getListUnion({ ...query, ...{ status: { $nin: onlineStoryStatus }, online_time: { $in: times } } }, { online_time: -1 });
    return convertKey(list);
  }
  // 如果查询条件没有需求状态，默认不查 发布完成 已归档
  let list: any = {};
  if (query.id) {
    list = await storys.getListPagination(query, { online_time: -1 }, page, pageSize);
  } else if (!params.status) {
    list = await storys.getListPagination({ ...query, ...{ status: { $nin: onlineStoryStatus } } }, { online_time: -1 }, page, pageSize);
  } else {
    list = await storys.getListPagination(query, { online_time: -1 }, page, pageSize);
  }
  // 字段名优化
  return {
    ...list,
    data: convertKey(list.data),
  };
};

// 删除某一项
export const syncStoryDelete = async (params: any) => {
  const result = await storys.deleteOne(params);
  return result;
};

// 更新某一项
export const syncStoryUpdate = async (params: any) => {
  const result = await storys.updateAdd({ $set: params }, { id: params.id });
  return result;
};

// 添加、更新tapd关联的项目
export const syncStroyUpdateRelation = async (params: any) => {
  // id：需求的id
  const { id, isEdit, ...props } = params;
  let result;
  // 更新
  if (typeof isEdit === 'number') {
    // db.find({ id: params.id }, { _id: 0, relation_projects: 1 }) 为何报错
    const res: any = await storys.findOne({ id: params.id });
    const { relation_projects } = res;
    relation_projects.splice(isEdit, 1, props);
    result = await storys.update({ relation_projects }, { id: params.id });
  } else {
    // 新增
    // 判断数据库是否存在已经录入的项目和分支，如果存在不支持再次添加。待开发
    result = await storys.updatePush({ relation_projects: props }, { id: params.id });
  }
  return result;
};

// 删除tapd关联的项目
export const syncStoryDeleteRelation = async (params: any) => {
  const res: any = await storys.findOne({ id: params.id });
  const { relation_projects } = res;
  relation_projects.splice(params.index, 1);
  const result = await storys.update({ relation_projects }, { id: params.id });
  return result;
};

// 创建合并分支
export const syncStoryCreateMergeBranch = async (params: { selectRows: { project_name: string; project: number | string; branch: string }; onlineTime: string }) => {
  // let mergeBranch = `develop_mergeProd_${dayjs().format('YYYYMMDD')}`;
  const { selectRows, onlineTime } = params;

  // 为每个project创建合并分支
  // const { length } = selectRows;
  // async function loop(index) {
  //   let i = index;
  //   if (i >= length) return;
  //   // 获取项目信息
  //   const res2: any = await syncProjectsSearch({ id: selectRows[i] });
  //   // 获取需求关联项目库里这个项目今天创建过合并分支了吗
  //   const count = await storyWithproject.getCount({ online_time: onlineTime });
  //   if (count > 0) {
  //     mergeBranch += `_${count + 1}`;
  //   }
  //   console.log(mergeBranch);
  //   const { default_branch, name } = res2[0];
  // 创建合并分支
  // const res1 = await syncPostNewBranch({
  //   id: selectRows[i],
  //   ref: default_branch,
  //   branch: mergeBranch,
  // });
  // 往需求关联项目表里插入合并分支
  const res3 = await addRelative({
    project_name: selectRows.project_name,
    project_id: Number(selectRows.project),
    unionBranch: selectRows.branch,
    isMergeToMain: 0,
    mr: undefined,
    online_time: onlineTime,
    pid: 0,
    branch: selectRows.branch,
  });
  return res3;
  // loop((i += 1));
  // }
  // await loop(0);
};

// 代码检查
export const syncCodeCheck = async (params: { branch: string; project_id: string }) => {
  const { branch, project_id } = params;
  const branchInfo: any = await getSingleBranch({ private_token: privateToken, id: project_id, branch });
  const projectInfo = (await syncProjectsSearch({ id: project_id })) || [];
  if (branchInfo && projectInfo && projectInfo[0]) {
    const {
      commit: { author_name, author_email },
    } = branchInfo as { commit: { author_name: string; author_email: string } };
    const user = {
      name: author_name,
      email: author_email,
    };
    const { http_url_to_repo: git, name } = projectInfo[0];
    const res = await sonarApi.post('/api/triggerCheck', { branch, name, git, user });
    console.log(res);
  }
};
